package com.zoho.daliansheng.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zoho.daliansheng.common.U8SystemRecord;
import com.zoho.daliansheng.common.ZohoRecord;
import com.zoho.daliansheng.config.CRMPathConfig;
import com.zoho.daliansheng.config.DatasourceEnum;
import com.zoho.daliansheng.config.U8SystemPathConfig;
import com.zoho.daliansheng.dlcr.DlcrU8WebService;
import com.zoho.daliansheng.dlcr.DlcrU8WebServiceSoap;
import com.zoho.daliansheng.dlcr.QueryRetInfo;
import com.zoho.daliansheng.utils.CrmApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    ZohoRecord zohoRecord;

    U8SystemRecord u8SystemRecord;

    U8SystemPathConfig u8SystemPathConfig;

    CRMPathConfig crmPathConfig;

    public UserServiceImpl(ZohoRecord zohoRecord, U8SystemRecord u8SystemRecord, U8SystemPathConfig u8SystemPathConfig, CRMPathConfig crmPathConfig) {
        this.zohoRecord = zohoRecord;
        this.u8SystemRecord = u8SystemRecord;
        this.u8SystemPathConfig = u8SystemPathConfig;
        this.crmPathConfig = crmPathConfig;
    }

    @Override
    public void synUser() {

        /*
         * 1 获取CRM 用户
         */
        List<JSONObject> crmData = CrmApiUtil.getAllUserData(zohoRecord.getAccessToken());
        System.out.println("crmData.size() = " + crmData.size());
        /*
         * 2 同步ERP人员
         */
        try {
            synU8Data(crmData, DatasourceEnum.GONG_CHANG.getWebServiceUrl(), DatasourceEnum.GONG_CHANG.getCompanyName(), DatasourceEnum.GONG_CHANG.getAccountCode());
            synU8Data(crmData, DatasourceEnum.SU_ZHOU.getWebServiceUrl(), DatasourceEnum.SU_ZHOU.getCompanyName(), DatasourceEnum.SU_ZHOU.getAccountCode());
            synU8Data(crmData, DatasourceEnum.CHANG_ZHOU.getWebServiceUrl(), DatasourceEnum.CHANG_ZHOU.getCompanyName(), DatasourceEnum.CHANG_ZHOU.getAccountCode());
            synU8Data(crmData, DatasourceEnum.DA_LIAN.getWebServiceUrl(), DatasourceEnum.DA_LIAN.getCompanyName(), DatasourceEnum.DA_LIAN.getAccountCode());
            synU8Data(crmData, DatasourceEnum.XIN_CAI_LIAO.getWebServiceUrl(), DatasourceEnum.XIN_CAI_LIAO.getCompanyName(), DatasourceEnum.XIN_CAI_LIAO.getAccountCode());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void synU8Data(List<JSONObject> crmData, String webServiceUrl, String companyName, String accountCode) throws MalformedURLException {

        log.info("同步【" + companyName + "】");

        String synModuleName = "users";

        // 1 模块最大版本号
        Map<String, String> map = CrmApiUtil.getMaxVersion(zohoRecord.getAccessToken(), synModuleName, accountCode);
        String versionCrmId = map.get("id");
        int maxVersion = Integer.parseInt(map.get("maxVersion"));

        // 3 获取ERP数据
        DlcrU8WebService webService = new DlcrU8WebService(new URL(webServiceUrl));
        DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
        QueryRetInfo queryRetInfo = api.queryHrHiPersonByVersion(maxVersion);
        int queryMaxVersion = queryRetInfo.getMaxVersion();
        JSONArray jsonArray = JSONArray.parseArray(queryRetInfo.getJson());
        if (jsonArray.size() > 0) {
            // 4 比较数据
            List<JSONObject> updateList = new ArrayList<>();
            List<JSONObject> batchPerson = jsonArray.toJavaList(JSONObject.class);
            for (JSONObject person : batchPerson) {
                String erpUserName = person.getString("cpsn_name"); // 人员姓名
                List<JSONObject> searchList = crmData.stream().filter(object -> Objects.nonNull(object.getString("full_name")) && object.getString("full_name").equals(erpUserName)).collect(Collectors.toList());
                if (searchList.size() > 0) {
                    JSONObject jsonObject = searchList.get(0);
                    String crmId = jsonObject.getString("id");
                    person.put("crmId", crmId);
                    updateList.add(person);
                }
            }

            // 5 字段映射
            List<JSONObject> crm_updateUserList = getCrmMappingData(updateList, accountCode);
            System.out.println("crm_updateUserList.size() = " + crm_updateUserList.size());

            // 6 批量操作
            for (JSONObject jsonObject : crm_updateUserList) {
                CrmApiUtil.updateUserData(zohoRecord.getAccessToken(), jsonObject);
            }

            // 7 最大版本号回传
            if (queryMaxVersion != maxVersion) {
                CrmApiUtil.saveMaxVersion(zohoRecord.getAccessToken(), versionCrmId, queryMaxVersion, crmPathConfig.getMaxVersionModuleName());
            }
        }
    }

    private List<JSONObject> getCrmMappingData(List<JSONObject> erpList, String accountCode) {
        List<JSONObject> list = new ArrayList<>();
        for (JSONObject erpData : erpList) {
            JSONObject crmData = new JSONObject();
            String crmId = erpData.getString("crmId");
            crmData.put("id", crmId);
            if (accountCode.equals(DatasourceEnum.GONG_CHANG.getAccountCode())) { // 工厂
                crmData.put("erp5", erpData.getString("cpsn_num"));  // erp人员编码
                crmData.put("erp11", erpData.getString("cdept_num")); // 部门编码
            } else if (accountCode.equals(DatasourceEnum.SU_ZHOU.getAccountCode())) { // 苏州
                crmData.put("erp6", erpData.getString("cpsn_num"));  // erp人员编码
                crmData.put("erp8", erpData.getString("cdept_num")); // 部门编码
            } else if (accountCode.equals(DatasourceEnum.CHANG_ZHOU.getAccountCode())) { // 常州
                crmData.put("erp4", erpData.getString("cpsn_num"));  // erp人员编码
                crmData.put("erp12", erpData.getString("cdept_num")); // 部门编码
            } else if (accountCode.equals(DatasourceEnum.DA_LIAN.getAccountCode())) { // 大连
                crmData.put("erp3", erpData.getString("cpsn_num"));  // erp人员编码
                crmData.put("erp10", erpData.getString("cdept_num")); // 部门编码
            } else if (accountCode.equals(DatasourceEnum.XIN_CAI_LIAO.getAccountCode())) { // 新材料
                crmData.put("erp7", erpData.getString("cpsn_num"));  // erp人员编码
                crmData.put("erp13", erpData.getString("cdept_num")); // 部门编码
            }
            list.add(crmData);
        }
        return list;
    }
}
